import axios from 'axios';
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/user';

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10000
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    // 如果有token，添加到请求头
    if (userStore.token) {
      config.headers['token'] = userStore.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理错误响应
    const { response } = error;
    if (response && response.data) {
      message.error(response.data.message || '请求失败');
    } else if (!response) {
      message.error('网络错误，请检查网络连接');
    }
    return Promise.reject(error);
  }
);

export default service; 